/* $RCSFile: Recycler.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Recycler/Recycler.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:59  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Configuration;
using AddonNice.UI.WebControls;
using AddonNice.Settings;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Recycler
{
	/// <summary>
	///	Allow recovering deleted modules
	/// </summary>
	public partial class Recycler : PortalModuleControl
	{
		/// <summary>
		/// Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

        private void Page_Load(object sender, EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler Page_Load IsPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),ModuleTraceSwitch.Sw.Info);
		}


        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler RadGrid1_NeedDataSource RebindReason: {0}.", e.RebindReason),ModuleTraceSwitch.Sw.Info);
            try
            {
                if (RadGrid1.MasterTableView.SortExpressions.Count == 0)
                {
                    RadGrid1.MasterTableView.SortExpressions.AddSortExpression("DateDeleted DESC");
                }
                GridSortExpression exp  =   RadGrid1.MasterTableView.SortExpressions[0];
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler RadGrid1_NeedDataSource Sort FieldName: {0}.", exp.FieldName),ModuleTraceSwitch.Sw.Info);
                DataTable tb            = new RecyclerDB().GetModulesInRecycler(portalSettings.PortalID, exp.FieldName);
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler RadGrid1_NeedDataSource Table count: {0}.", tb.Rows.Count),ModuleTraceSwitch.Sw.Info);
                RadGrid1.DataSource = tb;
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Recycler RadGrid1_NeedDataSource ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
		}



        protected override void OnADNDeleteInModule(EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler OnADNDeleteInModule BEG RadGrid1.SelectedItems: {0}.",RadGrid1.SelectedItems),ModuleTraceSwitch.Sw.Info);
            
            foreach(GridDataItem dataItem  in RadGrid1.SelectedItems)
            {
                string modStr           =   dataItem.OwnerTableView.DataKeyValues[dataItem.ItemIndex]["ModuleID"].ToString();
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler OnADNDeleteInModule BEG Module: {0}", modStr),ModuleTraceSwitch.Sw.Info);
                DeleteModule(modStr);
            }
            base.OnADNDeleteInModule(e);
            RadGrid1.DataSource =   null;
            RadGrid1.Rebind();
            SetMessage("Modules deleted");
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Recycler OnADNDeleteInModule END.",ModuleTraceSwitch.Sw.Info);
        }

        /// <summary>
		/// The RadGrid1_ItemDeleted is used to definitively delete a portal module from db
		/// </summary>
        void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem   =   (GridDataItem)e.Item;
            string modStr           =   dataItem.OwnerTableView.DataKeyValues[dataItem.ItemIndex]["ModuleID"].ToString();
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler RadGrid1_DeleteCommand Module: {0}", modStr),ModuleTraceSwitch.Sw.Info);
            try
            {
                DeleteModule(modStr);
                RadGrid1.DataSource =   null;
                RadGrid1.Rebind();
                SetMessage("Module " + modStr + " deleted");
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Recycler RadGrid1_DeleteCommand Module: {0}, ex: {1}", modStr, ex), ModuleTraceSwitch.Sw.Info);
                e.Canceled = true;
                SetMessage("Error deleting module " + modStr);
            }
        }
        
        void DeleteModule(string modStr)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler DeleteModule Module: {0}", modStr),ModuleTraceSwitch.Sw.Info);
            try
            {
                ModulesDB mdb       =   new ModulesDB();
                int modId           =   int.Parse(modStr);
                mdb.DeleteModule(modId,Guid.Empty);
             }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Recycler DeleteModule Module: {0}, ex: {1}", modStr, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
		}

		
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{E928F47B-A131-4a33-88D5-D5D6E7A94B36}");
			}
        }

        #region Telerik specific utilities

        private void DisplayMessage(string text)
        {
            RadGrid1.Controls.Add(new LiteralControl(string.Format("<span style='color:red'>{0}</span>", text)));
        }

        private void SetMessage(string message)
        {
            gridMessage = message;
        }

        private string gridMessage = null;
        /// <summary>
        /// Just here to display a message down in the grid
        /// </summary>
        protected void RadGrid1_DataBound(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(gridMessage))
            {
                DisplayMessage(gridMessage);
            }
        }

        /// <summary>
        /// Just here to hide the create button of Telerik CommandItem
        /// </summary>
        void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridCommandItem)
            {
                // the link button
                LinkButton btn  =   (LinkButton)e.Item.FindControl("InitInsertButton");
                if ( btn != null )
                    btn.Visible     =   false;
                //the image
                Control img     =   e.Item.FindControl("AddNewRecordButton");
                if ( img != null )
                    img.Visible =   false;

            }
        }

        #endregion Telerik specific utilities

        #region Web Form Designer generated code

        public override void Page_PreInit(object sender, EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Recycler Page_PreInit BEG.",ModuleTraceSwitch.Sw.Info);
            DeleteBtn.SkinID = "Delete_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            base.Page_PreInit(sender, e);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Recycler Page_PreInit END",ModuleTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Recycler OnInit BEG IsPostBack: {0}, IsInAsyncPostBack: {1}", IsPostBack,IsInAsyncPostBack),ModuleTraceSwitch.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Recycler OnInit END",ModuleTraceSwitch.Sw.Info);
		}
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Recycler InitializeComponent BEG.",ModuleTraceSwitch.Sw.Info);
			Load                    +=  new EventHandler(Page_Load);
			RadGrid1.NeedDataSource +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.DeleteCommand  +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.DataBound      +=  new EventHandler(RadGrid1_DataBound);
            RadGrid1.ItemCreated    +=  new GridItemEventHandler(RadGrid1_ItemCreated);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Recycler InitializeComponent END.",ModuleTraceSwitch.Sw.Info);
		}


		#endregion
	}
}
